/**
 * Created by sa on 2015/4/15.
 */

var moment = require('moment');
var _ = require('underscore');

module.exports = function (task_phone) {

  /**
   * 更新或者添加数据
   * @param id
   * @param cb
   */
  task_phone.updModel = function (model, cb) {
    task_phone.upsert(model, function (error, model) {
      cb(error, model);
    });
  }


  /**
   * 获取数据
   * @param id
   * @param cb
   */
  task_phone.findModelById = function (id, cb) {

    task_phone.findById(id, function (error, data) {
      cb(error, data);
    });
  }


  /**
   * 保存数据
   * @param model
   * @param cb
   */
  task_phone.saveModel = function (model, cb) {
    task_phone.create([
      model
    ], function (err, data) {
      cb(err, this.coverTime(data));
    });
  }

  /**
   * 删除数据根据id
   * @param model
   * @param cb
   */
  task_phone.delById = function (id, cb) {

    task_phone.findById(id, function (error, data) {
      if (error || data == null) {
        return cb(0);
      }
      task_phone.destroyById(id, function (err) {
        if (err) {
          return cb(0);
        }
        return cb(1);
      });
    });
  }

  /**
   * 获取列表，根据主拨手机号码
   * @param model
   * @param cb
   */
  task_phone.getList = function (phone, cb) {

    task_phone.find({where: {phone: phone} , order: 'id DESC'}, function (error, models) {
      if (error) {
        return cb(error, coverTime(models));
      }
      cb(error, this.coverTime(models));
    });
  }


  /**
   * 获取要执行的任务列表
   * @param model
   * @param cb
   */
  task_phone.getExcList = function (cb) {

    task_phone.find({where: {state: 1} , order: 'id asc'}, function (error, models) {
      if (error) {
        return cb(error, models);
      }
      cb(error,models);
    });
  }


  /**
   * 转换时间
   * @param models
   * @returns {Array}
   */
  task_phone.coverTime = function(models){

    if(_.isArray(models)){
      var array = new Array();
      _.each(models , function(element, index, list){
        var model = element.__data;
        model.excTime = moment(model.excTime).format('YYYY-MM-DD HH:mm:ss');
        model.setTime = moment(model.setTime).format('YYYY-MM-DD HH:mm:ss');
        model.createTime = moment(model.createTime).format('YYYY-MM-DD HH:mm:ss');
        array.push(model)
      });
      return array;
    }else if(models != null){
      var model = models.__data;
      model.excTime = moment(model.excTime).format('YYYY-MM-DD HH:mm:ss');
      model.setTime = moment(model.setTime).format('YYYY-MM-DD HH:mm:ss');
      model.createTime = moment(model.createTime).format('YYYY-MM-DD HH:mm:ss');
      return model;
    }
  }
}
